package logic

import (
	"context"
	"fmt"
	"tieba/models/cache"
	"tieba/models/mysql"

	"tieba/tiebarpc/internal/svc"
	"tieba/tiebarpc/tiebarpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type ForgetLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewForgetLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ForgetLogic {
	return &ForgetLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ForgetLogic) Forget(in *tiebarpc.ForgetRequest) (*tiebarpc.ForgetResponse, error) {
	// todo: add your logic here and delete this line
	var user mysql.User
	mysql.DB.Debug().Where("mobile = ?", in.Mobile).Find(&user)
	get, _ := cache.Rdb.Get(cache.Ctx, "send"+in.Mobile).Result()
	if get != in.SendCode {
		return nil, fmt.Errorf("验证码错误")
	}
	if user.ID == 0 {
		return nil, fmt.Errorf("该账号不存在")
	}
	if in.Password == user.Password {
		return nil, fmt.Errorf("密码和旧密码一样")
	}
	user.Password = in.Password
	mysql.DB.Debug().Updates(&user)
	return &tiebarpc.ForgetResponse{
		UserId: int64(user.ID),
	}, nil
}
